<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MeetingSeriesVO } from '#/api/meeting/series/model';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { Button, Modal, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  meetingSeriesInfo,
  meetingSeriesPage,
  meetingSeriesRemove,
  meetingSeriesUpdateStatus,
} from '#/api/meeting/series';
import { DetailsModal } from '#/components/modal';
import { TableSwitch } from '#/components/table';

import seriesImgTableDrawer from './components/series-img-table-drawer.vue';
import { columns, detailsSchema, querySchema } from './data';
import seriesDrawer from './series-drawer.vue';

const { hasAccessByCodes } = useAccess();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
  // columns: columns(),
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await meetingSeriesPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'meeting-series-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 详情
const [MeetingSeriesInfoModal, modalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

function handlePreview(record: MeetingSeriesVO) {
  modalApi.setData(record);
  modalApi.open();
}

// 新增编辑
const [SeriesDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: seriesDrawer,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(row: MeetingSeriesVO) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleDelete(row: MeetingSeriesVO) {
  await meetingSeriesRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: MeetingSeriesVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await meetingSeriesRemove(ids);
      await tableApi.query();
    },
  });
}

// 图片管理
const [SeriesImgTableDrawer, seriesImgTableDrawerApi] = useVbenDrawer({
  connectedComponent: seriesImgTableDrawer,
  destroyOnClose: true,
});

function handleViewImgList(row: MeetingSeriesVO) {
  seriesImgTableDrawerApi.setData({ id: row.id, name: row.name });
  seriesImgTableDrawerApi.open();
}

async function statusUpdate(row: MeetingSeriesVO) {
  const data = {
    id: row.id,
    status: row.status,
  };
  await meetingSeriesUpdateStatus(data);
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="会议系列列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['meeting:series:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['meeting:series:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #name="{ row }">
        <Button
          type="link"
          :href="`https://www.iteschina.com/zh-cn/meeting/${row.id}`"
          target="_blank"
        >
          {{ row.name }}
        </Button>
      </template>
      <template #status="{ row }">
        <TableSwitch
          v-model:value="row.status"
          :api="() => statusUpdate(row)"
          :disabled="!hasAccessByCodes(['meeting:series:edit'])"
          @reload="tableApi.query()"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['meeting:series:query']"
            @click.stop="handlePreview(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button
            v-access:code="['meeting:series:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <ghost-button @click.stop="handleViewImgList(row)">
            图片管理
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['meeting:series:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <MeetingSeriesInfoModal
      :columns="detailsSchema()"
      :api="meetingSeriesInfo"
      :width="700"
      :label-width="150"
    />
    <SeriesDrawer @reload="tableApi.query()" />
    <SeriesImgTableDrawer />
  </Page>
</template>
